const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

const app = express();
const port = process.env.PORT || 8888;//我喜欢8000

// 连接数据库
mongoose.connect(process.env.MONGODB_URI)
    .then(() => console.log('MongoDB连接成功'))
    .catch(err => console.error('MongoDB连接失败:', err));

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

// 路由
app.use('/api/users', require('./routes/userRoutes'));

// 根路由
app.get('/', (req, res) => {
  res.send('Welcome to Express Application!');
});

// 示例 API 路由
app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello from Express!' });
});

// POST 请求示例
app.post('/api/data', (req, res) => {
  const data = req.body;
  res.json({
    message: 'Data received successfully',
    data: data
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        success: false,
        message: '服务器错误',
        error: process.env.NODE_ENV === 'development' ? err.message : '请联系管理员'
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});
